/**
 * User: alesj
 * Date: 18.3.2006
 * Time: 15:37:52
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.alesj.blade.login;

import com.alesj.blade.data.Admin;
import com.alesj.blade.data.User;
import com.alesj.blade.util.Utils;
import org.jboss.seam.Seam;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.contexts.Context;
import org.jboss.seam.core.Actor;
import org.jboss.seam.ejb.SeamInterceptor;

import javax.ejb.Interceptors;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.Serializable;

/**
 * @author <a href="mailto:ales.justin@genera-lynx.com">Ales Justin</a>
 */
@Stateless
@Name("login")
@LoginIf
@Interceptors(SeamInterceptor.class)
public class LoginAction implements Login, Serializable {

    @PersistenceContext
    private EntityManager em;

    @In
    Context sessionContext;

    @In(create = true)
    Actor actor;

    String username = "";
    String password = "";

    public String getUserName() {
        return username;
    }

    public void setUserName(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @LoginIf(outcome = {"admin", "customer"})
    public String login() {
        try {
            User found =
                    (User)em.createQuery("from User u where u.userName = :userName and u.password = :password")
                            .setParameter("userName", username)
                            .setParameter("password", password)
                            .getSingleResult();

            sessionContext.set("currentUser", found);

            actor.setId(found.getUserName());

            if (found instanceof Admin) {
                sessionContext.set("currentUserIsAdmin", true);
                actor.getGroupActorIds().add("reviewers");
                return "admin";
            } else {
                return "customer";
            }
        }
        catch (Exception e) {
            Utils.warnUser("loginErrorPrompt", null);
            return "notok";
        }
    }

    public String logout() {
        Seam.invalidateSession();
        sessionContext.set("currentUser", null);
        sessionContext.set(LoginIfInterceptor.LOGIN_KEY, null);
        return "done";
    }

}
